package com.example.martian.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.martian.config.util.RedisUtils;
import com.example.martian.mapper.IndexMapper;
import com.example.martian.mapper.RedPacketMapper;
import com.example.martian.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional(rollbackFor = Exception.class)
public class RedPackService {

    @Autowired
    private ExchangeRateUtils exchangeRateUtils;

    @Autowired
    private RedPacketMapper redPacketMapper;

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HongBaoUtils hongBaoUtils;

    private static final String URL = "http://api.tianapi.com/txapi/fxrate/index?key=0d9d342a93446f794927f8100d164632&" +
            "fromcoin=USD&tocoin=CNY&money=1";

    //红包币种和人民币汇率
    @Transactional
    public Object checkCoin() throws IOException {
        String exchange = "";
//        JSONObject jsonObject = exchangeRateUtils.exchangeRate(URL);
        JSONObject objectJson = null;
//        JSONObject object = jsonObject.getJSONArray("newslist").getJSONObject(0);
        String money = "6.61";
        JSONArray jsonArray = new JSONArray();
        //查询币种
        List<Map<String, Object>> mapList = redPacketMapper.checkExchange();
        List<Map<String, Object>> mapObj = indexMapper.checkExchange();
        for (Map<String, Object> maps : mapList) {
            String cmcCoin = maps.get("cmc_coin").toString();
            if (cmcCoin.equals("ETH_USDT")){
                cmcCoin = "USDT";
                exchange = exchangeRateUtils.exchange(cmcCoin);
            }else {
                exchange = exchangeRateUtils.exchange(maps.get("cmc_coin").toString());
            }
            objectJson = new JSONObject();
            objectJson.put("coinId",maps.get("cmc_id"));
            objectJson.put("coin",maps.get("cmc_coin"));
            objectJson.put("service_charge",maps.get("cmc_service_charge"));
            objectJson.put("logo",maps.get("cmc_logo"));
            String CNY = BigDecimalUtils.mul(exchange, money, 8);
            objectJson.put("exchangeRate", CNY);
            jsonArray.add(objectJson);
        }
        return Utils.toJSON("访问成功", jsonArray.toString(), "0");
    }

    /**
     * @coin        币种
     * @sendMoney   红包金额
     * @address     发红包账户
     * @type        红包类型（1，普通红包 2，暗号红包 3，专属红包）
     * @number      红包个数
     * @cipher      红包暗号
     * @typeMoney   红包规则（1，平均 2，随机）
     * @jypassword  交易密码
     **/

    //塞钱进红包
    @Transactional(rollbackFor = Exception.class)
    public Object sendRedPacket(String coin,String sendMoney, String address,Integer typeMoney,
                                Integer type, Integer number, String cipher, Integer jypassword,String addressUid) {
        String sub = "";
        long timeMillis = System.currentTimeMillis();
        Pattern pattern = Pattern.compile("([0-9]*){2,14}$");
        boolean matches = pattern.matcher(cipher).matches();
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = null;
        Integer jYpassword = redPacketMapper.selectJYpassword(address);
        String invitationcode = redPacketMapper.selectcInvitationcode(address);
        String moneyCoin = indexMapper.selectMoneyByCoin(coin, address);
        String privateCipher = invitationcode+"+"+timeMillis;
        boolean exists = redisUtils.exists(cipher);
        if (new BigDecimal(sendMoney).compareTo(BigDecimal.ZERO) == -1) {
            return Utils.toJSON("非法数量", jsonArray.toString(), "1");
        }
        if (!jypassword.equals(jYpassword)) {
            return Utils.toJSON("交易密码错误，请重新输入", Utils.toJSONmap(), "3");
        }
        if (!(BigDecimalUtils.compare(sendMoney, moneyCoin))) {
            if (type == 1) {
                if (typeMoney == 1) {
                    //计算平均值
                    Double div = BigDecimalUtils.div(Double.parseDouble(sendMoney),Double.parseDouble(number.toString()), 8);
                    List<Map<String, Object>> list = hongBaoUtils.repacketMap(div, coin, number, invitationcode, addressUid, address,sendMoney);
                    hongBaoUtils.redPacketRedis(cipher,list);
                }
                if (typeMoney == 2){
                    List<Double> hongbao = hongBaoUtils.hongbao(new BigDecimal(sendMoney).doubleValue(), number, 0.00000003);
                    List<Map<String, Object>> list = new ArrayList<>();
                    for (int i = hongbao.size() - 1; i >= 0; i--) {
                        map = new HashMap<>();
                        map.put("value", hongbao.get(i));
                        map.put("coin", coin);
                        map.put("number",number);
                        map.put("invitationcode",invitationcode);
                        map.put("addressUid",addressUid);
                        map.put("address",address);
                        map.put("sendMoney",sendMoney);
                        list.add(map);
                    }
                    hongBaoUtils.redPacketRedis(cipher,list);
                }
                //计算发送人剩余金额
                sub = BigDecimalUtils.sub(moneyCoin, sendMoney, 8);
                indexMapper.updateCoinMoney(address, coin, sub);
                exchangeRateUtils.insertRedPacket(coin,sendMoney,addressUid,number,0,address,type,0,cipher);
            } else if (type == 2) {
                if (cipher != null && !cipher.trim().isEmpty() && matches) {
                    if (exists){
                        return Utils.toJSON("暗号已被占用,请重新输入",Utils.toJSONmap(),"5");
                    }else {
                        if (typeMoney == 1){
                            //计算平均值
                            Double div = BigDecimalUtils.div(Double.parseDouble(sendMoney),Double.parseDouble(number.toString()), 8);
                            List<Map<String, Object>> list = hongBaoUtils.repacketMap(div, coin, number, invitationcode, addressUid, address,sendMoney);
                            hongBaoUtils.redPacketRedis(cipher,list);
                        }
                        if(typeMoney == 2){
                            List<Double> hongbao = hongBaoUtils.hongbao(new BigDecimal(sendMoney).doubleValue(), number, 0.00000003);
                            List<Map<String, Object>> list = new ArrayList<>();
                            for (int i = hongbao.size() -1;i >= 0;i--){
                                map = new HashMap<>();
                                map.put("value", hongbao.get(i));
                                map.put("coin", coin);
                                map.put("number",number);
                                map.put("invitationcode",invitationcode);
                                map.put("addressUid",addressUid);
                                map.put("address",address);
                                map.put("sendMoney",sendMoney);
                                list.add(map);
                            }
                            hongBaoUtils.redPacketRedis(cipher,list);
                            //计算发送人剩余金额
                        }
                        sub = BigDecimalUtils.sub(moneyCoin, sendMoney, 8);
                        indexMapper.updateCoinMoney(address, coin, sub);
                        exchangeRateUtils.insertRedPacket(coin,sendMoney,addressUid,number,0,address,type,0,cipher);
                    }
                } else {
                    return Utils.toJSON("暗号不能为空或者是2—14个数字,不包含符号",Utils.toJSONmap(),"4");
                }
            }
        }else {
            return Utils.toJSON("可用金额不足", jsonArray.toString(), "2");
        }
        jsonObject.put("invitationcode",privateCipher);
        jsonObject.put("remainingSum",moneyCoin);
        return Utils.toJSON("红包已备好",jsonObject.toString(),"0");
    }


    //暗号红包或普通红包
    @Transactional(rollbackFor = Exception.class)
    public Object cipherHongbao(String cipher,String address){
        String accountUid = indexMapper.selectAddressUid(address);
        Object robHongbao = hongBaoUtils.robHongbaoUtil(cipher, address,accountUid);
        return robHongbao;
    }


    //收红包记录
    @Transactional(rollbackFor = Exception.class)
    public Object selectRedPacketRoll(String address){
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> mapList = redPacketMapper.selectRedPacketRoll(address);
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("addressUid",map.get("cmc_addressUid"));
            jsonObject.put("number",map.get("cmc_number"));
            jsonObject.put("money",map.get("cmc_coinMoney"));
            jsonObject.put("coin",map.get("cmc_coin"));
            jsonObject.put("remainNumber",map.get("cmc_remainNumber"));
            jsonObject.put("sj",map.get("cmc_sj"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //发红包记录
    @Transactional(rollbackFor = Exception.class)
    public Object selectRedPacket(String address) {
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> mapList = redPacketMapper.selectRedPacket(address);
        for (Map<String, Object> map : mapList) {
            jsonObject = new JSONObject();
            jsonObject.put("addressUid", map.get("cmc_addressUid"));
            jsonObject.put("number", map.get("cmc_number"));
            jsonObject.put("money", map.get("cmc_money"));
            jsonObject.put("coin", map.get("cmc_coin"));
            jsonObject.put("remainNumber", map.get("cmc_remainNumber"));
            jsonObject.put("sj", map.get("cmc_sj"));
            jsonObject.put("type",map.get("cmc_type"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功", jsonArray.toString(), "0");
    }
}
